const ws = require('ws');
const http = require('http');
const express = require('express')
const app = express()
const port = 9000

//initialize a simple http server
const server = http.createServer(app);
//initialize the WebSocket server instance
const wss = new ws.Server({ server });

let packets = 0;

wss.on('connection', (s) => {
	console.log("ws client connected");
	s.on('message', (message, isBinary) => {
		console.log('received: isBinary=%s type=%s length=%d packets=%d', isBinary, typeof(message), message.length, packets);

		if (isBinary) { // Audio Data
			s.send(message); // echo back

			if (++packets % 20 == 0) {
				const rpc = {
					jsonrpc: "2.0",
					method: "text",
					params: {
						confidence: 0.99,
						text: "你好",
					}
				}
				const data = JSON.stringify(rpc);
				console.log("sending: ", data);
				s.send(data);
			}
		} else {
			const rpc = JSON.parse(message)
			console.log(rpc);
	
			if (rpc.method == "start") {
				handle_start(s, rpc);
			}
		}
	});
});

function handle_start(s, rpc) {
	reply = {
		jsonrpc: "2.0",
		id: rpc.id,
		result: {
			code: 200,
			message: "OK",
			audio: "sendrecv",
		}
	}

	console.log("send", reply);
	str = JSON.stringify(reply);
	s.send(str);
}

wss.on('close', () => {
	console.log("closed");
	packets = 0;
});

server.listen(port, () => {
	console.log(`Example ASR Server listening at http://localhost:${port}`)
})
